//
//  MapRootViewController.m
//  Cycling
//
//  Created by cjg.mini on 2023/3/2.
//

#import "MapRootViewController.h"
#import <Mapbox/Mapbox.h>
#import <Mapbox/MGLAnnotation.h>
#import "MapRequest.h"
#import "MapSearchListView.h"
#import <MapKit/MKMapView.h>
#import "CSMapAnimationModel.h"

#import <MapboxDirections/MapboxDirections.h>
#import <MapboxCoreNavigation/MapboxCoreNavigation.h>
#import <MapboxNavigation/MapboxNavigation.h>

#import "Cycling-Swift.h"

@interface MapRootViewController ()
<
 MGLMapViewDelegate
,MGLLocationManager
>
@property (nonatomic, strong) MGLMapView *mapView;
@property (nonatomic, strong) UILabel *placeLabel; // 动态搜索文字
@property (nonatomic, strong) MapSearchListView *searchListView;
@end

/**
 地图取点
 */
@interface MapRootViewController ()

@property (nonatomic, strong) MGLUserLocation *startPoint;
@property (nonatomic, strong) CSMapAnimationModel *destinationModel;

@end
/**
 地图定位
 */
@interface MapRootViewController (CSLocationManager)


@end

@implementation MapRootViewController
@synthesize authorizationStatus, delegate, headingOrientation;

- (void)dealloc {
    [_mapView removeFromSuperview];
    _mapView.delegate = nil;
    _mapView = nil;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    UIView *whiteView = [[UIView alloc] initWithFrame:CGRectMake(20, SafeAreaTopHeight + 10, SCREEN_W - 40, 30)];
    whiteView.backgroundColor = [UIColor whiteColor];
    [whiteView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tap)]];
    [self.view addSubview:whiteView];
    
    UIImageView *iv = [[UIImageView alloc] initWithFrame:CGRectMake(10, 7.5, 15, 15)];
    iv.image = [UIImage imageNamed:@"sousuo"];
    [whiteView addSubview:iv];
    
    self.placeLabel = [[UILabel alloc] initWithFrame:CGRectMake(31, 0, whiteView.ce_width - iv.right - 16, 26)];
    _placeLabel.text = @"搜索";
    _placeLabel.textColor = rgb(176, 176, 176);
    _placeLabel.font = [UIFont systemFontOfSize:16];
    [whiteView addSubview:_placeLabel];
    whiteView.layer.cornerRadius = 4;

    [self.view addSubview:self.mapView];
    
    [self loadData];
}

- (void)loadData {
    NSString *parh = [[NSBundle mainBundle] pathForResource:@"GeoJSONSourceExample" ofType:@"geojson"];
    NSURL *filePath = [NSURL fileURLWithPath:parh];
    
    NSData *data = [NSData dataWithContentsOfURL:filePath];
    NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    NSLog(@"%@",str);

    MGLShape *shape = [MGLShape shapeWithData:data encoding:NSUTF8StringEncoding error:nil];
    MGLShapeSource *source = [[MGLShapeSource alloc] initWithIdentifier:@"1234" shape:shape options:nil];
    MGLLineStyleLayer *layer = [[MGLLineStyleLayer alloc] initWithIdentifier:@"1234" source:source];
    layer.lineColor =  [NSExpression expressionForConstantValue:UIColor.redColor];
    layer.lineWidth = [NSExpression expressionForConstantValue:@10];
    layer.lineGapWidth = [NSExpression expressionForConstantValue:@10];
    [self.mapView.style addSource:source];
    [self.mapView.style addLayer:layer];
    
    [self.mapView setCamera:[self.mapView cameraThatFitsShape:shape direction:0 edgePadding:UIEdgeInsetsZero] animated:YES];
    
    [MapRequest getCyclingListWithPage:1 address:@"shanghai" day:@"week" time:@"2023-3-25" result:^(NSDictionary * _Nonnull dic) {
        
//        NSString *parh = [[NSBundle mainBundle] pathForResource:@"blueprint_style" ofType:@"json"];
//        NSURL *filePath = [NSURL fileURLWithPath:parh];
        
//        NSData *data = [NSData dataWithContentsOfURL:filePath];
//        NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
//        NSArray *json = [[MKGeoJSONDecoder alloc] geoJSONObjectsWithData:data error:nil];
//        NSLog(@"%@", str);
//
//        [self.mapView setStyleURL:filePath];

//        MGLStyleLayer *layer = [[MGLStyleLayer alloc] ];
//        [self.mapView.style addLayer:<#(nonnull MGLStyleLayer *)#>]
//        CLLocationCoordinate2DMake(<#CLLocationDegrees latitude#>, <#CLLocationDegrees longitude#>)
//        @[@23,34];
//        CLLocationCoordinate2D a = CLLocationCoordinate2DMake(39.980528, 116.306745);
//        CLLocationCoordinate2D b = CLLocationCoordinate2DMake(39.980528, 116.306745);

//        MGLPolygonFeature *feature = [[MGLPolygonFeature alloc] insertCoordinates:<#(nonnull const CLLocationCoordinate2D *)#> count:<#(NSUInteger)#> atIndex:<#(NSUInteger)#>];
//        MGLShapeSource *source = [[MGLShapeSource alloc] initWithIdentifier:@"geoJSON-data-source" shape:feature options:nil];
//        MGLSource *source = [[MGLSource alloc] initWithIdentifier:"werwre"];
//        MGLStyleLayer *layer = [[MGLStyleLayer alloc] ]
//        [self.mapView.style addLayer:(nonnull MGLStyleLayer *)];
//        MGLAnnotationView *ann = [[MGLAnnotationView alloc] init];
//        ann.annotation = [[MGLAnnotation alloc] init];
//        MGLAnnotationView *annotation = [[MGLAnnotationView alloc] init];
//        MGLPolyline *line = [[MGLPolyline alloc] init];
//        annotation.annotation.coordinate = CLLocationCoordinate2DMake(39.980528, 116.306745);
//        annotation.annotation.title = @"1";
//
//        [self.mapView. addAnnotations:@[annotation.annotation]];
//        [self.mapView.style addSource:(nonnull MGLSource *)]
        
    }];
}

- (void)tap {
    MapSearchListView *searchListView = [[MapSearchListView alloc] initWithFrame:self.view.bounds];
    [self.view addSubview:searchListView];
    self.searchListView = self.searchListView;
}

- (MGLMapView *)mapView {
    if (_mapView == nil) {
        //设置地图的 frame 和 地图个性化样式
        _mapView = [[MGLMapView alloc] initWithFrame:CGRectMake(0, 50 + SafeAreaTopHeight, SCREEN_W, self.view.ce_height - 50 - SafeAreaTopHeight) styleURL:[NSURL URLWithString:@"mapbox://styles/mapbox/streets-v10"]];
        _mapView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
        //设置地图默认显示的地点和缩放等级
        [_mapView setCenterCoordinate:CLLocationCoordinate2DMake(77.018178, 116.306745) zoomLevel:15 animated:YES];
        //显示用户位置
        _mapView.showsUserLocation  = YES;
        //定位模式
        _mapView.userTrackingMode   = MGLUserTrackingModeFollow;
        //是否倾斜地图
        _mapView.pitchEnabled       = YES;
        //是否旋转地图
        _mapView.rotateEnabled      = NO;
        //代理
        _mapView.delegate           = self;
        
        UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapGestureReceived:)];
        [_mapView addGestureRecognizer:tapGesture];
    }
    return _mapView;
}


- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:NO];

}
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:NO];

}

#pragma mark - 地图定位
- (void)dismissHeadingCalibrationDisplay {
    
}

- (void)requestAlwaysAuthorization {
    
}

- (void)requestWhenInUseAuthorization {
    
}

- (void)startUpdatingHeading {
    
}

- (void)startUpdatingLocation {
    
}

- (void)stopUpdatingHeading {
    
}

- (void)stopUpdatingLocation {
    
}

- (void)mapView:(MGLMapView *)mapView didUpdateUserLocation:(MGLUserLocation *)userLocation
{
    if(!self.startPoint) {
        self.startPoint = userLocation;
    }
}

- (void)mapViewDidFinishLoadingMap:(MGLMapView *)mapView
{
    [mapView setUserTrackingMode:MGLUserTrackingModeNone animated:YES completionHandler:^{
        
    }];
}

- (void)mapView:(MGLMapView *)mapView didFinishLoadingStyle:(MGLStyle *)style
{
//    [self loadData];
}

@end

/**
 地图选点
 */
@implementation MapRootViewController (AddPointInMap)

- (void)tapGestureReceived:(UITapGestureRecognizer *)tapGesture
{
    CGPoint locationPoint = [tapGesture locationInView:self.mapView];
    CLLocationCoordinate2D location = [self.mapView convertPoint:locationPoint toCoordinateFromView:self.mapView];
    
    [self.mapView removeAnnotation:self.destinationModel];
    self.destinationModel = [[CSMapAnimationModel alloc] initWithCoordinator:location];
    [self.mapView addAnnotation:self.destinationModel];
    
    [self requestCycleRoutes];
}

- (void)requestCycleRoutes
{
    if(!self.startPoint || !self.destinationModel) {
        return;
    }
    
//    [CSMapManager requestRoutesWithFromLocation:self.startPoint.location.coordinate destinationLocation:self.destinationModel.coordinate presentedVC:self];
    YQMapRoutesViewController *routesVC = [YQMapRoutesViewController new];
    [self.navigationController pushViewController:routesVC animated:YES];
    [routesVC setupLocationsWithFromLocation:self.startPoint.location.coordinate endLocation:self.destinationModel.coordinate];
}

@end
